package com.fwzc.giuseppe.activity;

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import com.fwzc.giuseppe.R;
import com.fwzc.giuseppe.Api.Api;
import com.fwzc.giuseppe.adapter.AllOrderAdapter;
import com.fwzc.giuseppe.adapter.AllOrderAdapter.onSure;
import com.fwzc.giuseppe.base.BaseActivity;
import com.fwzc.giuseppe.entity.Goods;
import com.fwzc.giuseppe.util.OrderState;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

@SuppressLint("InflateParams") 
public class AllOrderActivity extends BaseActivity implements OnClickListener,OnRefreshListener,onSure{
	private ListView myListView;
	private AllOrderAdapter adapter;
	private ArrayList<Goods> datas = new ArrayList<Goods>();
	private SwipeRefreshLayout refreshLayout;
	private ProgressDialog load;
	private HttpUtils httpUtil;
	private String userId;
	private int suitId;
	private Dialog sure_dialog;
	private RelativeLayout sure_view;
	private Button certain;
	@SuppressLint("HandlerLeak") 
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg.what == 1){
				refreshLayout.setRefreshing(false);
			}
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_all_order);

		initBar();
		initView();
		initListView();
		initClick();
	}

	private void initView() {
		// 网络请求相关
		httpUtil = new HttpUtils();
		load = new ProgressDialog(this);
		load.setMessage(getResources().getString(R.string.deal));
		load.setCancelable(false);
		userId = getSharedPreferences("user", Activity.MODE_PRIVATE).getString(
				"userId", "");
		//头部
		actionbar_side_name.setText("全部订单");
		iv_actionbar_side_left.setVisibility(View.VISIBLE);
		iv_actionbar_side_left.setOnClickListener(this);
		
		sure_view = (RelativeLayout)LayoutInflater.from(this).inflate(R.layout.dialog_sure, null);
		certain = (Button)sure_view.findViewById(R.id.sure);
		sure_dialog = new Dialog(this);
		sure_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		sure_dialog.setContentView(sure_view);
		
		myListView = (ListView) findViewById(R.id.all_order);
		refreshLayout = (SwipeRefreshLayout)findViewById(R.id.refreshLayout);
		refreshLayout.setOnRefreshListener(this);
		refreshLayout.setColorSchemeResources(android.R.color.holo_green_dark,android.R.color.holo_green_light,android.R.color.holo_orange_light,android.R.color.holo_red_light);
	}

	private void initListView() {
//		for (int i = 0; i < 12; i++) {
//			Goods order = new Goods();
//			switch (i % 4) {
//			case 0:
//				order.operation = OrderOperation.WAINT_PAYMENT;
//				break;
//			case 1:
//				order.operation = OrderOperation.WAIT_RECEIVE;
//				break;
//			case 2:
//				order.operation = OrderOperation.WAINT_COMMENT;
//				break;
//			case 3:
//				order.operation = OrderOperation.CHANGE_RETURN;
//				break;
//			default:
//				break;
//			}
//			datas.add(order);
//		}
		adapter = new AllOrderAdapter(this, datas);
		myListView.setAdapter(adapter);
		sendRequest();
	}

	private void sendRequest(){
		RequestParams params = new RequestParams("UTF-8");
		params.addBodyParameter("userId", userId);
		params.addBodyParameter("type", "0");
		// 发送json类型的数据
		// params.setBodyEntity(new StringEntity(jsonStr,charset));
		httpUtil.send(HttpRequest.HttpMethod.POST, Api.ORDER_LIST, params,
				new RequestCallBack<String>() {

					@Override
					public void onStart() {
						load.show();
					}

					@Override
					public void onFailure(HttpException arg0, String response) {
						load.dismiss();
						showToast("加载数据失败");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseStr) {
						try {
							JSONObject response = new JSONObject(responseStr.result);
							int resultCode = response.getInt("resultCode");
							if (resultCode == 0) {
								JSONArray ja = response.getJSONArray("dataList");
								for (int i = 0; i < ja.length(); i++) {
									JSONObject jo = ja.getJSONObject(i);
									String orderNumber = jo.getString("orderNumber");
									int orderType = jo.getInt("orderType");
									JSONArray content = jo.getJSONArray("detailList");
									for (int j = 0; j < content.length(); j++) {
										JSONObject orderInfo = content.getJSONObject(j);
										Goods goods = new Goods();
										goods.goods_code = orderNumber;
										goods.operation = orderType;
										goods.goods_id = orderInfo.getInt("suitid");
										goods.goods_name = orderInfo.getString("name");
										goods.price = orderInfo.getString("price");
										goods.number = orderInfo.getString("amount");
										goods.goods_url = orderInfo.getString("imgurl");
										int flage = orderInfo.getInt("afterSalesType");
										goods.state = flage == 5?OrderState.Return:OrderState.CHANGE;
										datas.add(goods);
									}
								}
								adapter.notifyDataSetChanged();
								if(refreshLayout.isRefreshing()){
									refreshLayout.setRefreshing(false);
								}
								load.dismiss();
							}else{
								load.dismiss();
								showToast(response.getString("msg"));
							}
						} catch (JSONException e) {
							load.dismiss();
							showToast("解析出错");
						}

					}
				});
	}
	
	private void orderConfirm(final int order_id){
		RequestParams params = new RequestParams("UTF-8");
		params.addBodyParameter("userId", userId);
		params.addBodyParameter("suitId", String.valueOf(order_id));
		// 发送json类型的数据
		// params.setBodyEntity(new StringEntity(jsonStr,charset));
		httpUtil.send(HttpRequest.HttpMethod.POST, "http:www.baidu.com",
				params, new RequestCallBack<String>() {

					@Override
					public void onStart() {
						load.show();
					}

					@Override
					public void onFailure(HttpException arg0, String response) {
						load.dismiss();
						showToast("确认收货失败");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseStr) {
						JSONObject response;
						try {
							response = new JSONObject(responseStr.result);
							int resultCode = response.getInt("resultCode");
							if(resultCode == 0){
								datas.remove(order_id);
								adapter.notifyDataSetChanged();
								showToast("已确认收货");
							}
						} catch (JSONException e) {
							load.dismiss();
							showToast("解析出错");
						}
					}
				});
	}
	
	private void initClick(){
		certain.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				sure_dialog.dismiss();
				orderConfirm(suitId);
			}
		});
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_actionbar_side_left:
			finish();
			break;

		default:
			break;
		}
	}

	@Override
	public void onRefresh() {
		refreshLayout.setRefreshing(true);
		datas.clear();
		sendRequest();
	}

	@Override
	public void click(int suit_id) {
		suitId = suit_id;
		sure_dialog.show();
	}
}
